<template>
    <div class="left-top-container">
        <!-- 图表区域 -->
        <div class="chart-container">
            <v-chart class="chart" :option="chartOption" v-if="JSON.stringify(chartOption) !== '{}'"
                style="height: 100%;" />
        </div>
        <div class="time-info">
            <!-- <span class="time-item">当前时间：{{ currentTime }}</span> -->
            <span class="time-item">日出时间：{{ sunriseTime }}</span>
            <span class="time-item">日落时间：{{ sunsetTime }}</span>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, watch, nextTick, onBeforeUnmount } from 'vue'
import { dateInfo } from '@/utils/dateInfo'
import { graphic } from 'echarts/core'

const activeTimeType = ref('day')
const chartOption = ref({})
const loading = ref(false)

// 当前时间
const currentTime = ref('')
// 日出日落时间
const sunriseTime = ref('')
const sunsetTime = ref('')

// 更新时间的定时器
let timeTimer: NodeJS.Timeout | null = null

// 更新当前时间和日出日落时间
const updateTimeInfo = () => {
    const now = new Date()
    currentTime.value = now.toLocaleTimeString('zh-CN', { hour12: false })
    
    // 获取今天的日期
    const today = now.getMonth() + 1 + '月' + now.getDate() + '日'
    const todayData = dateInfo.find(item => item.date === today)
    
    if (todayData) {
        sunriseTime.value = todayData.sunrise
        sunsetTime.value = todayData.sunset
    }
}


// 模拟数据（备用）
const mockData = reactive({
    year: {
        xData: ['2019', '2020', '2021', '2022', '2023', '2024'],
        yData: [1200, 1800, 2400, 3200, 4100, 4800] as (number | null)[]
    },
    month: {
        xData: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
        yData: [320, 280, 450, 520, 680, 720, 850, 900, 750, 650, 480, 380] as (number | null)[]
    },
    day: {
        xData: ['00时', '01时', '02时', '03时', '04时', '05时', '06时', '07时', '08时', '09时', '10时', '11时', '12时', '13时', '14时', '15时', '16时', '17时', '18时', '19时', '20时', '21时', '22时', '23时'],
        yData: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] as (number | null)[]
    }
})

const switchTimeType = (type: string) => {
    activeTimeType.value = type
    updateChart()
}

const updateChart = () => {


    chartOption.value = {
        tooltip: {
            trigger: 'axis',
            backgroundColor: 'rgba(0, 0, 0, 0.8)',
            borderColor: 'rgba(124, 189, 207, 0.8)',
            textStyle: {
                color: '#ffffff'
            },
            formatter: function (params: any) {
                return `${params[0].name}<br/> 瞬时功率: ${params[0].value?params[0].value:0}kW`
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            top: '15%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: mockData['day'].xData,
            axisLine: {
                lineStyle: {
                    color: 'rgba(255, 255, 255, 0.3)'
                }
            },
            axisLabel: {
                color: '#7EB7FD',
                fontSize: 12
            },
            splitLine: {
                show: true,
                lineStyle: {
                    color: 'rgba(31, 99, 163, 0.2)'
                }
            }
        },
        yAxis: {
            type: 'value',
            name: '瞬时功率(kW)',
            nameTextStyle: {
                color: '#7EB7FD',
                fontSize: 12
            },
            axisLine: {
                lineStyle: {
                    color: 'rgba(255, 255, 255, 0.3)'
                }
            },
            axisLabel: {
                color: '#7EB7FD',
                fontSize: 12
            },
            splitLine: {
                show: true,
                lineStyle: {
                    color: 'rgba(31, 99, 163, 0.2)'
                }
            }
        },
        series: [
            {
                name: '瞬时功率',
                type: 'line',
                smooth: true,
                symbol: 'circle',
                symbolSize: 6,
                data: mockData['day'].yData,
                lineStyle: {
                    color: '#00d4ff',
                    width: 3
                },
                itemStyle: {
                    color: '#00d4ff',
                    shadowColor: '#00d4ff',
                    shadowBlur: 10
                },
                areaStyle: {
                    color: new graphic.LinearGradient(0, 0, 0, 1, [
                        {
                            offset: 0,
                            color: 'rgba(0, 212, 255, 0.6)'
                        },
                        {
                            offset: 1,
                            color: 'rgba(0, 212, 255, 0.1)'
                        }
                    ])
                }
            }
        ]
    }
}

const timer = ref()
onMounted(async () => {
    // 初始化时间信息
    updateTimeInfo()
    
    // 启动时间更新定时器，每秒更新一次
    timeTimer = setInterval(updateTimeInfo, 1000)
    
    await nextTick(() => {
        // 获取接口数据
        // fetchPowerCurveData()

        // 备用：根据今天的日期，在dateInfo 中找到对应日期的数据
        const today = new Date().getMonth() + 1 + '月' + new Date().getDate() + '日'
        const todayData = dateInfo.find(item => item.date === today)
        console.log('todayData', todayData)

        // 如果接口数据获取失败，使用模拟数据
        timer.value = setTimeout(() => {
            updateChart()
            clearTimeout(timer.value)
        }, 2000)
    })
})

// 组件卸载时清理定时器
onBeforeUnmount(() => {
    if (timeTimer) {
        clearInterval(timeTimer)
        timeTimer = null
    }
})

const init = (module: any) => {
    let data = JSON.parse(module)
    let list: (number | null)[] = []

    if (module) {
        // 获取今天的日期
        const today = new Date().getMonth() + 1 + '月' + new Date().getDate() + '日'
        const todayData = dateInfo.find(item => item.date === today)
        
        if (todayData) {
            // 解析日出和日落时间
            const sunriseTime = todayData.sunrise // 格式: "7:25:48"
            const sunsetTime = todayData.sunset   // 格式: "17:02:19"
            
            // 将时间字符串转换为小时数（24小时制）
            const sunriseHour = parseInt(sunriseTime.split(':')[0])
            const sunsetHour = parseInt(sunsetTime.split(':')[0])
            
            data.forEach((item: any, index: number) => {
                const currentHour = index // 假设数据按小时顺序排列，index对应小时
                
                // 如果当前时间在日出之前或日落之后，设置value为0
                if (currentHour < sunriseHour || currentHour > sunsetHour || item.value == 0 || item.value == null) {
                    list.push(null)
                } else {
                    list.push(Number(item.value))
                }
            })
        } else {
            // 如果找不到今天的日期数据，使用原始逻辑
            data.forEach((item: any) => {
                list.push(Number(item.value))
            })
        }
        
        mockData['day'].yData = list as (number | null)[]
    }

}

const upData = (module: any) => {
    let data = JSON.parse(module)
    let list: (number | null)[] = []

    if (module) {
        // 获取今天的日期
        const today = new Date().getMonth() + 1 + '月' + new Date().getDate() + '日'
        const todayData = dateInfo.find(item => item.date === today)
        
        if (todayData) {
            // 解析日出和日落时间
            const sunriseTime = todayData.sunrise // 格式: "7:25:48"
            const sunsetTime = todayData.sunset   // 格式: "17:02:19"
            
            // 将时间字符串转换为小时数（24小时制）
            const sunriseHour = parseInt(sunriseTime.split(':')[0])
            const sunsetHour = parseInt(sunsetTime.split(':')[0])
            
            data.forEach((item: any, index: number) => {
                const currentHour = index // 假设数据按小时顺序排列，index对应小时
                
                // 如果当前时间在日出之前或日落之后，设置value为0
                if (currentHour < sunriseHour || currentHour > sunsetHour || item.value == 0 || item.value == null) {
                    list.push(null)
                } else {
                    list.push(Number(item.value))
                }
            })
        } else {
            // 如果找不到今天的日期数据，使用原始逻辑
            data.forEach((item: any) => {
                list.push(Number(item.value))
            })
        }

        mockData['day'].yData = list as (number | null)[]
    }
    
    updateChart()
}

defineExpose({
    init,
    upData
})


</script>

<style lang="less" scoped>
.left-top-container {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    padding: 10px;
    box-sizing: border-box;
}

.time-switch {
    display: flex;
    justify-content: center;
    margin-bottom: 15px;
    background: rgba(0, 30, 60, 0.6);
    border-radius: 20px;
    padding: 4px;

    .switch-btn {
        padding: 6px 16px;
        margin: 0 2px;
        border-radius: 16px;
        color: #7EB7FD;
        font-size: 12px;
        cursor: pointer;
        transition: all 0.3s ease;

        &:hover {
            background: rgba(0, 212, 255, 0.2);
            color: #00d4ff;
        }

        &.active {
            background: linear-gradient(90deg, #00d4ff 0%, #0099cc 100%);
            color: #ffffff;
            box-shadow: 0 2px 8px rgba(0, 212, 255, 0.4);
        }
    }
}

.time-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    // padding: 8px 16px;
    margin-bottom: 10px;
    // background: rgba(0, 30, 60, 0.6);
    border-radius: 8px;
    // border: 1px solid rgba(0, 212, 255, 0.3);
    
    .time-item {
        color: #7EB7FD;
        font-size: 12px;
        font-weight: 500;
        text-shadow: 0 0 4px rgba(126, 183, 253, 0.5);
        
        &:first-child {
            color: #00d4ff;
            font-weight: 600;
        }
        
        &:nth-child(2) {
            color: #ffa500;
        }
        
        &:nth-child(3) {
            color: #ff6b6b;
        }
    }
}

.chart-container {
    flex: 1;
    height: 100%;

    .chart {
        width: 100%;
        height: 100%;

        :deep(.vue-echarts-inner) {
            div:nth-child(1) {
                height: 100% !important;
            }
        }
    }
}
</style>